/*
 * Copyright (c) 2021 Talkweb Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>
#include <unistd.h>

#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio.h"

#include "wifi_ap_service.h"

static unsigned int lastTickCount = 0;
volatile char start_wifi_config_flag = 0;

/**
 * @brief USER按键响应事件函数，即GPIO5中断回调函数。
 *        因物理按键存在硬件抖动影响，需要做软件消抖处理。
 * @param arg
 */
void GpioApIsrFunc(char *arg)
{
    (void)arg;

    //按键软件消抖，消除按键抖动
    unsigned int tickCount = osKernelGetTickCount();
    unsigned int count = tickCount - lastTickCount;
    lastTickCount = tickCount;

    if (count > 50)
    {
        if (start_wifi_config_flag == 0)
        {
            start_wifi_config_flag = 1;
        }
        else
        {
            start_wifi_config_flag = 0;
        }
    }

    return;
}

/**
 * @brief 初始化核心板USER按键中断事件，USER按键连接到GPIO5
 */
void InitGpioIsrFunc(void)
{
    unsigned int ret = 0;

    IoTGpioInit(IOT_GPIO_IO_GPIO_5);
    IoTIoSetFunc(IOT_GPIO_IO_GPIO_5, IOT_IO_FUNC_GPIO_5_GPIO);
    IoTIoSetPull(IOT_GPIO_IO_GPIO_5, IOT_IO_PULL_UP);
    ret = IoTGpioSetDir(IOT_GPIO_IO_GPIO_5, IOT_GPIO_DIR_IN);
    if (ret != 0)
    {
        printf("===== ERROR ======gpio -> hi_gpio_set_dir1 ret:%d\r\n", ret);
        return;
    }
    ret = IoTGpioRegisterIsrFunc(IOT_GPIO_IO_GPIO_5, IOT_INT_TYPE_EDGE,
                                 IOT_GPIO_EDGE_RISE_LEVEL_HIGH, GpioApIsrFunc, NULL);

    return;
}

/**
 * @brief WiFiAP热点创建程序,CMSIS线程回调函数
 * @param arg 线程参数
 */
void *WifiApServiceTask(const char *arg)
{
    (void)arg;

    InitGpioIsrFunc();

    while (start_wifi_config_flag == 0)
    {
        usleep(300000);
    }

    printf("[Talkweb Niobe] wifi_start_softap \r\n");
    wifi_start_ap();

    osThreadExit();
    return NULL;
}

/**
 * @brief WiFi-AP模式案例入口函数
 */
static void EntryWifiApService(void)
{

    printf("\n[Talkweb Niobe] Entry Wifi Ap Service!\n");

    osThreadAttr_t attr;
    attr.name = "wifiApServiceTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 4096;
    attr.priority = osPriorityAboveNormal4;

    if (osThreadNew((osThreadFunc_t)WifiApServiceTask, NULL, &attr) == NULL)
    {
        printf("[Talkweb Niobe] Falied to create WifiApServiceTask!\n");
    }
    return;
}

APP_FEATURE_INIT(EntryWifiApService);
